<template>
  <div class="detail-container">
    <!-- 顶部导航 -->
    <van-nav-bar
        title="事件详情"
        left-text="返回"
        left-arrow
        @click-left="$router.go(-1)"
    />

    <!-- 应急预案按钮 -->
    <div class="emergency-plan">
      <van-button
          type="primary"
          block
          icon="warning-o"
          @click="showYuanDialog">
        应急预案
      </van-button>
    </div>

    <!-- 应急预案弹窗 -->
    <van-dialog
        v-model="yuanDialogVisible"
        title="应急预案"
        show-cancel-button
        @confirm="yuanDialogVisible = false">
      <div class="yuan-content">
        <div v-if="form.yuan" class="yuan-text">{{ form.yuan }}</div>
        <van-empty v-else description="暂无应急预案内容" />
      </div>
    </van-dialog>

    <!-- 主表单 -->
    <van-form class="main-form">
      <van-loading v-if="loading" vertical>加载中...</van-loading>

      <!-- 基本信息部分 -->
      <div class="form-section">
        <div class="section-title">基本信息</div>

        <van-field
            label="事件类型"
            v-model="form.tname"
            readonly
        />

        <van-field
            label="事件位置"
            v-model="form.address"
            readonly
        />

        <van-field
            label="应急成员"
            v-model="form.name"
            placeholder="请输入应急成员"
        />

        <van-field
            label="联系电话"
            v-model="form.phone"
            type="tel"
            placeholder="请输入联系电话"
        />

        <van-field
            label="结束时间"
            is-link
            readonly
            @click="showTimePicker = true"
            :value="form.endTime"
        />

        <van-popup v-model="showTimePicker" position="bottom">
          <van-datetime-picker
              v-model="form.endTime"
              type="datetime"
              @confirm="showTimePicker = false"
              @cancel="showTimePicker = false"
          />
        </van-popup>
      </div>

      <!-- 记录信息部分 -->
      <div class="form-section">
        <div class="section-title">记录信息</div>

        <!-- 视频上传 -->
        <van-field label="视频记录">
          <template #input>
            <van-uploader
                v-model="videoFiles"
                :max-count="1"
                :after-read="afterVideoRead"
                accept="video/*"
            >
              <div v-if="form.record" class="video-container">
                <video
                    :src="form.record"
                    class="video-player"
                    controls
                    @error="handleVideoError">
                  您的浏览器不支持视频播放
                </video>
              </div>
              <van-button v-else icon="plus" type="primary">上传视频</van-button>
            </van-uploader>
          </template>
        </van-field>

        <van-field
            label="过程描述"
            type="textarea"
            v-model="form.script"
            rows="4"
            placeholder="请输入处置过程描述"
        />

        <!-- 图片上传 -->
        <van-field label="现场照片">
          <template #input>
            <van-uploader
                v-model="imageFiles"
                :max-count="1"
                :after-read="afterImageRead"
                accept="image/*"
            >
              <img v-if="form.pic" :src="form.pic" class="preview-img">
              <van-button v-else icon="plus" type="primary">上传图片</van-button>
            </van-uploader>
          </template>
        </van-field>
      </div>

      <!-- 提交按钮 -->
      <div class="form-actions">
        <van-button
            type="primary"
            block
            :loading="submitting"
            @click="update">
          提交处置记录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "detail1",
  data() {
    return {
      yuanDialogVisible: false,
      showTimePicker: false,
      loading: false,
      submitting: false,
      id: null,
      imageFiles: [],
      videoFiles: [],
      form: {
        tname: '',
        address: '',
        name: '',
        phone: '',
        endTime: '',
        record: '',
        script: '',
        pic: '',
        yuan: ""
      },
    }
  },
  methods: {
    showYuanDialog() {
      if (!this.form.yuan) {
        this.$toast.fail('暂无应急预案内容')
        return
      }
      this.yuanDialogVisible = true
    },

    findAll() {
      if (!this.id) {
        this.$toast.fail('ID不能为空')
        return
      }

      this.loading = true
      axios.post(`http://localhost:9999/api-safe-service/detail/findById?id=${this.id}`)
          .then(res => {
            if (res.data?.code === 1) {
              this.form = res.data.data
            } else {
              this.$toast.fail(res.data.message || '获取数据失败')
            }
          })
          .catch(() => {
            this.$toast.fail('网络请求失败')
          })
          .finally(() => {
            this.loading = false
          })
    },

    update() {
      if (!this.form.script) {
        this.$toast.fail('请填写处置过程描述')
        return
      }

      this.form.status = 1
      this.submitting = true

      axios.post("http://localhost:9999/api-safe-service/detail/update", this.form)
          .then(() => {
            this.$toast.success("保存成功")
            this.$router.push('/safe')
          })
          .catch(() => {
            this.$toast.fail("保存失败")
          })
          .finally(() => {
            this.submitting = false
          })
    },

    async afterVideoRead(file) {
      try {
        const formData = new FormData()
        formData.append('file', file.file)
        const res = await axios.post("http://localhost:9999/api-safe-service/oss/upload", formData)
        this.form.record = res.data
        this.$toast.success('视频上传成功')
      } catch (error) {
        this.$toast.fail('视频上传失败')
      }
    },

    async afterImageRead(file) {
      try {
        const formData = new FormData()
        formData.append('file', file.file)
        const res = await axios.post("http://localhost:9999/api-safe-service/oss/upload", formData)
        this.form.pic = res.data
        this.$toast.success('图片上传成功')
      } catch (error) {
        this.$toast.fail('图片上传失败')
      }
    },

    handleVideoError() {
      this.$toast.fail('视频加载失败')
    },
  },

  created() {
    this.id = this.$route.query.id
    if (this.id) {
      this.findAll()
    } else {
      this.$toast.fail('未获取到ID参数')
      this.$router.push('/safe')
    }
  }
}
</script>

<style scoped>
.detail-container {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 20px;
}

.emergency-plan {
  padding: 16px;
}

.main-form {
  background: #fff;
  margin: 0 16px;
  padding: 16px;
  border-radius: 8px;
}

.form-section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #323233;
  margin-bottom: 16px;
  padding-left: 8px;
  border-left: 3px solid #1989fa;
}

.video-container {
  width: 100%;
  height: 200px;
  overflow: hidden;
  border-radius: 4px;
}

.video-player {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.preview-img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
}

.form-actions {
  margin-top: 24px;
}

.yuan-content {
  padding: 16px;
  max-height: 60vh;
  overflow-y: auto;
}

.yuan-text {
  line-height: 1.6;
  color: #323233;
}
</style>